package com.wl.application.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author wl
 * @version 1.0
 * @date 2022/6/27
 * @description: 跨域过滤器  统一处理跨域(预检)被拦截的问题
 */
@Component
@Slf4j
public class OptionsCrossFilter {
    /**
     * 跨域过滤器
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); // 请求都中可以带任意的参数
        corsConfiguration.addAllowedMethod("*"); // 可以以任意的请求方式访问
        corsConfiguration.addAllowedOrigin("*"); //可以任意的域名访问
        corsConfiguration.setMaxAge(3600L); // 跨域的缓存的时间，-1代表如果禁用缓存
        //加允许传送cookie会出现报错
//        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

}
